package com.faiz.algorithm;

public class MaxProfit {
    public int maxProfit(int[] prices) {
        // 按照统一模板来处理
        int l = prices.length;
        int[][][] dp = new int[l][3][2];
        // basecase
        // dp[-1][0][0] = 0
        // dp[-1][k][0] = 0
        // dp[-1][0][1] = -inf
        // dp[-1][k][1] = -inf

        for (int i = 0; i < l; i++) {
            for (int k = 1; k < 3; k++) {
                if (i - 1 == -1) {
                    dp[0][0][0] = 0;
                    dp[0][0][1] = -prices[i];
                    dp[0][1][0] = 0;
                    dp[0][1][1] = -prices[i];
                    dp[0][2][0] = 0;
                    dp[0][2][1] = -prices[i];
                } else {
                    dp[i][k][0] = Math.max(dp[i - 1][k][0], dp[i - 1][k][1] + prices[i]);
                    dp[i][k][1] = Math.max(dp[i - 1][k][1], dp[i - 1][k - 1][0] - prices[i]);
                }
            }
        }
        return dp[l - 1][2][0];
    }

    public static void main(String[] args) {
        int[] prices = {3, 3, 5, 0, 0, 3, 1, 4};
        MaxProfit maxProfit = new MaxProfit();
        System.out.println(maxProfit.maxProfit(prices));
    }
}
